package sunsun.xiaoli.jiarebang.device;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.DeviceListBean;
import com.itboye.pondteam.custom.swipemenulistview.SwipeMenuListView;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.volley.ResultEntity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import sunsun.xiaoli.jiarebang.R;
import sunsun.xiaoli.jiarebang.app.App;
import sunsun.xiaoli.jiarebang.custom.VpSwipeRefreshLayout;

import static com.itboye.pondteam.utils.EmptyUtil.getSp;
import static sunsun.xiaoli.jiarebang.utils.MapToArrayList.buildArrayForMap;
import static sunsun.xiaoli.jiarebang.utils.MapToArrayList.buildArrayForMapForBindCamera;
import static sunsun.xiaoli.jiarebang.utils.Util.getNickName;


/**
 */
@SuppressLint("NewApi")
public class BindCameraDeviceActivity extends BaseActivity implements Observer, SwipeRefreshLayout.OnRefreshListener {
    App mApp;
    SwipeMenuListView mListView;
    ImageView img_back;

    RelativeLayout relyout;
    TextView txt_title;
    public String uid = "";
    UserPresenter userPresenter;
    public ArrayList<DeviceListBean> arrayList = new ArrayList<>();
    public int position;
    private ArrayList<HashMap<String, Object>> listItems;
    private String currentDid, currentType;
    VpSwipeRefreshLayout swipe_layout;
    public String extra;
    private SimpleAdapter listItemsAdapter;
    private String slave_did = "", slave_psw = "";
    private ArrayList<DeviceListBean> bindedMasterDevice;
    DeviceListBean cameraListBean = new DeviceListBean();
    int layout = R.layout.device_bindcamera_item;

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_bindcamera_device);
        mApp = (App) getApplication();
        mApp.mBindCameraDeviceUi = this;
        txt_title.setText(getString(R.string.myadvice));
        cameraListBean = (DeviceListBean) getIntent().getSerializableExtra("model");
        slave_did = cameraListBean.getDid();
        try {
            slave_psw = new JSONObject(cameraListBean.getExtra()).getString("pwd");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        userPresenter = new UserPresenter(this);
        uid = getSp(Const.UID);
        //设置向下拉多少出现刷新
        swipe_layout.setDistanceToTriggerSync(150);
        swipe_layout.setColorSchemeColors(getResources().getColor(R.color.main_green));
        swipe_layout.setOnRefreshListener(this);
        swipe_layout.setRefreshing(true);
        listItems = new ArrayList<>();
        listItemsAdapter = new SimpleAdapter(this, listItems,
                layout, new String[]{"ItemName", "ItemDid",
                "ItemSwitch", "ItemIcon", "ItemStatus"},
                new int[]{R.id.textView_dev_name, R.id.textView_dev_did,
                        R.id.imageView_dev_right_arrow, R.id.imageView_dev_logo, R.id.imageView_dev_bind});
        mListView.setAdapter(listItemsAdapter);
        //列表项短按键处理
        mListView.setOnItemClickListener((parent, view, position, id) -> {
            //将要绑定主设备的did
            currentDid = listItems.get(position).get("ItemDid").toString().substring(4);
            String checked = listItems.get(position).get("ItemSwitch").toString();//绑定状态
            if (checked.equals("0")) {
                userPresenter.cameraBind(getSp(Const.UID), currentDid, slave_did, "chiniao_wifi_camera", getNickName(slave_did), slave_psw);
            } else {
                userPresenter.cameraUnBind(getSp(Const.UID), currentDid, slave_did);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        getDeviceList();
    }


    public void getDeviceList() {
        userPresenter.getMyDeviceList(uid);
    }


    @SuppressLint("WrongConstant")
    public void refreshDeviceListTest() {
        ArrayList<HashMap<String, Object>> listItemsTemp = buildArrayForMap(arrayList, "chiniao_wifi_camera");
        mListView.setVisibility(View.VISIBLE);
        relyout.setVisibility(View.VISIBLE);
        listItems.clear();
        listItems.addAll(listItemsTemp);
//        listItemsAdapter.notifyDataSetChanged();
        if (listItems.size() > 0) {
            mListView.setVisibility(View.VISIBLE);
            relyout.setVisibility(View.VISIBLE);
        } else {
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
        }
    }

    @Override
    public void update(Observable o, Object data) {
        ResultEntity entity = handlerError(data);
        swipe_layout.setRefreshing(false);
        if (entity != null) {
            if (entity.getCode() != 0) {
                MAlert.alert(entity.getMsg());
            } else if (entity.getEventType() == UserPresenter.getMyDeviceList_success) {
                arrayList = (ArrayList<DeviceListBean>) entity.getData();
                if (arrayList != null) {
                    if (arrayList.size() > 0) {
                        refreshDeviceListTest();
                        //在获取从设备被绑定的设备列表
                        userPresenter.cameraQuery(uid, null, slave_did);
                    }
                }
            } else if (entity.getEventType() == UserPresenter.getMyDeviceList_fail) {

            } else if (entity.getEventType() == UserPresenter.cameraQuery_success) {
                bindedMasterDevice = (ArrayList<DeviceListBean>) entity.getData();
                if (bindedMasterDevice != null) {
                    //遍历是否已经绑定
                    ArrayList<HashMap<String, Object>> listItemsTemp = buildArrayForMapForBindCamera(arrayList, bindedMasterDevice);
                    listItems.clear();
                    listItems.addAll(listItemsTemp);
                    listItemsAdapter.notifyDataSetChanged();
                }
            } else if (entity.getEventType() == UserPresenter.cameraQuery_fail) {
                MAlert.alert(entity.getMsg());
            } else if (entity.getEventType() == UserPresenter.cameraBind_success) {
                MAlert.alert(entity.getData());
                getDeviceList();
            } else if (entity.getEventType() == UserPresenter.cameraBind_fail) {
                MAlert.alert(entity.getMsg());
            } else if (entity.getEventType() == UserPresenter.cameraUnBind_success) {
                MAlert.alert(entity.getData());
                getDeviceList();
            } else if (entity.getEventType() == UserPresenter.cameraUnBind_fail) {
                MAlert.alert(entity.getMsg());
            }
        }
    }

    @Override
    public void onRefresh() {
        getDeviceList();
    }
}
